package pwd.allen.androiddemo.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import io.reactivex.functions.Consumer;
import pwd.allen.androiddemo.R;
import pwd.allen.androiddemo.util.ToastUtil;

public class WebViewActivity extends AppCompatActivity implements View.OnClickListener {

    private WebView webView;
    private ProgressBar progressBar;

    private File file;
    private ImageView img;
    private int type;
    private String url;
    private String id,soclCrdtId,poolType;
    public static void actionStart(Context context, int type) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }

    public static void actionStart(Context context, int type, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("type",type);
        intent.putExtra("url",url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        findViewById(R.id.back).setOnClickListener(this);
        img = findViewById(R.id.img);
        img.setOnClickListener(this);
        init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(webView != null){
            webView.destroy();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

    private void init() {
        progressBar = findViewById(R.id.progress_bar);
        webView = findViewById(R.id.webview);
//        initWebView();
        String ua = webView.getSettings().getUserAgentString();
        webView.getSettings().setUserAgentString(ua + ";tyj_mobile");
        // 本地HTML里面有跨域的请求 原生webview需要设置之后才能实现跨域请求
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
//        String url = "http://192.168.118.101/test.html";
        String url = "file:///android_asset/test.html";

        webView.setWebViewClient(new MyWebViewClient());
//        webView.setWebChromeClient(new MyWebChromeClient());
        webView.getSettings().setJavaScriptEnabled(true); // 设置支持javascript脚本
        //增加一个接口，给html中的javaScript传送数据
        webView.addJavascriptInterface(this, "Android");
        webView.loadUrl(url);
    }

    /**
     * 初始化WebView网络设置
     */
    @SuppressLint("SetJavaScriptEnabled")
    @SuppressWarnings("deprecation")
    private void initWebView() {
        // 设置网路兼容模式
        WebSettings webSettings = webView.getSettings();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setBlockNetworkImage(false);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //自动打开js窗口，默认是false
        //webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //控制页面布局，有三个类型（该方法不好用，会出导致页面显示不全）
        webSettings.setAllowFileAccess(true); // 是否允许访问网络文件
        webSettings.setBuiltInZoomControls(true); // 是否允许内置的放大机制（这里如果设为false，则setDisplayZoomControls(true)和setSupportZoom(true)无效）
        webSettings.setDisplayZoomControls(false); //是否显示WebView缩放按钮
        webSettings.setSupportZoom(true); // 是否允许屏幕缩放控件和手势缩放
//        webSettings.setAppCacheEnabled(false);//是否使用缓存
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不加载缓存
        webSettings.setDomStorageEnabled(true);//DOM Storage
        webSettings.setUseWideViewPort(true);// 加载进来的页面自适应手机屏幕
        webSettings.setLoadWithOverviewMode(true); //和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.setBlockNetworkImage(false);//解决图片不显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        // 适应屏幕大小
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int mDensity = metrics.densityDpi;
        if (mDensity == 240) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == 160) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        } else if (mDensity == 120) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        } else if (mDensity == DisplayMetrics.DENSITY_XHIGH) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == DisplayMetrics.DENSITY_TV) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            progressBar.setProgress(newProgress);
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }
    }

    private class MyWebViewClient extends WebViewClient {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //返回true，网页在当前WebView中重载，false则调用浏览器打开
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //接收ssl错误，原因是网站网址是https开头，WebView不支持改网站证书
            //注意：这里一定要把super.onReceivedSslError()注释掉。这是因为WebViewClient的
            if(handler != null){
                handler.proceed(); //接受证书
            }
        }
    }

    /**
     * 如果打开了网页就返回上一个页面，没有打开网页按返回键就关闭当前页面
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 如果webView中有上一页页面，则返回webView的上一页，如果不设置的话会直接返回上个activity
            if (webView.canGoBack()) {
                webView.goBack(); //goBack()表示返回webView的上一页面
                return true;
            } else if (event.getAction() == KeyEvent.ACTION_DOWN) {
                this.finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void startCamare() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //path为保存图片的路径，执行完拍照以后能保存到指定的路径下
            file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + System.currentTimeMillis() + ".JPEG");
            file.getParentFile().mkdirs();
            Uri imageUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, 1);
        } else {
            Toast.makeText(this, "没有SD卡", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 不能直接加上@JavascriptInterface在js中调用，否则报错：java.lang.IllegalStateException: Must be called from main thread of fragment host
     * @param telPhone
     */
    private void call(String telPhone) {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.CALL_PHONE).subscribe(new Consumer<Boolean>() {
            @SuppressLint("MissingPermission")
            @Override
            public void accept(Boolean granted) throws Exception {
                if (granted) {
                    //showTelDialog(tel);
                    Intent intent = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + telPhone);
                    intent.setData(data);
                    intent.putExtra("packageName", WebViewActivity.this.getPackageName());//这里的包名是：com.cndatacom.abcmarketing
                    startActivity(intent);
                } else {
                    ToastUtil.show(WebViewActivity.this, "您拒绝了拨打电话权限，自动拨号失败");
                }
            }
        });
    }

    @JavascriptInterface
    public void callPhone(String telPhone){
        Message msg = new Message();
        msg.obj = telPhone;
        msg.arg1 = 1;
        handler.sendMessage(msg);
    }

    /**
     * 可以直接给h5返回字符串
     * @param msg
     * @return
     */
    @JavascriptInterface
    public String showToast(String msg) {
        msg = "hello world :" + msg;
        ToastUtil.show(this, msg);
        return msg;
    }

    //接口AndroidFunction的方法，JavaScript可以直接引用。
    @JavascriptInterface
    public void backToNative() {
        this.finish();
    }

    /**
     * 通过调用h5中的函数来传数据
     */
    @JavascriptInterface
    public void invokeJs() {
        // 调用js中的函数setText
        webView.post(new Runnable() {
            @Override
            public void run() {
                String rel = "{\n" +
                        "  \"name\":\"android\",\n" +
                        "  \"age\":20\n" +
                        "}";
                webView.loadUrl(String.format("javascript:setText(%s)", rel));
            }
        });
    }

    /**
     * 打开视频
     * @param url
     */
    @JavascriptInterface
    public void videoPlayer(String url) {
        VideoPlayerActivity.actionStart(this, url);
    }



    private Handler handler =  new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg != null && msg.arg1 == 1){
                //拨打电话
                call(msg.obj.toString());
            }
        }
    };

}
